package com.xxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxx.entity.MPage;
import com.xxx.entity.Order;
import com.xxx.dao.OrderDao;
import com.xxx.entity.dto.OrderDto;
import com.xxx.entity.query.OrderQuery;
import com.xxx.entity.save.OrderSave;
import com.xxx.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xxx
 * @since 2024-11-24
 */
@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderDao, Order> implements IOrderService {

    @Autowired
    private OrderDao orderDao;
    @Override
    public MPage selectByPage(Integer current, Integer size) {
        int total = orderDao.selectCount(null);
        List<OrderDto> list = orderDao.selectByPage((current-1)*size,size);
        MPage page = MPage.builder()
                .current(current)
                .size(size)
                .total(total)
                .pages(total/size+total%size>0?1:0)
                .records(list)
                .build();
        return page;
    }

    @Override
    public MPage selectByCondition(OrderQuery orderQuery) {
        int current = orderQuery.getCurrent();
        int size = orderQuery.getSize();
        orderQuery.setCurrent((current-1)*size);
        List<OrderDto> list = orderDao.selectByCondition(orderQuery);
        int total = list.size();
        MPage page = MPage.builder()
                .current(current)
                .size(size)
                .total(total)
                .pages(total/size+total%size>0?1:0)
                .records(list)
                .build();
        return page;
    }

    @Override
    public Boolean addProduces(OrderSave orderSave) {
        Order order = Order.builder()
                        .createTime(orderSave.getCreateTime())
                        .userId(orderSave.getUserId())
                        .totalAmount(orderSave.getTotalAmount())
                        .build();
        Boolean flag1 = orderDao.insert(order) > 0;
        orderSave.setOrderId(order.getOrderId());
        Boolean flag2 = orderDao.addProduces(orderSave);
        return flag1 && flag2;
    }
}
